package com.finalproject.ui;
/**
 * DietarySummary class for the UI
 * Has Pie chart
 * Has StackBarChart
 */
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GradientPaint;
import java.util.Calendar;
import java.util.List;
import javax.swing.BorderFactory;
import javax.swing.JPanel;import org.jfree.ui.*;
import org.jfree.chart.*;
import org.jfree.data.category.*;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import com.finalproject.entity.CardHolder;
import com.finalproject.entity.CardHolderDatabase;
import com.finalproject.entity.CardHolderDatabase.CardHolderDatabaseObserver;
import com.finalproject.entity.DietaryEntry;
import com.finalproject.entity.DietaryProfile;
import com.finalproject.entity.DietaryProfile.DietaryProfileObserver;

public class UIDietarySummary extends JPanel implements
		CardHolderDatabaseObserver, DietaryProfileObserver {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	// private static String title="My Calories Consumed for last " +
	// UIConstants.CHART_DAYS + " days";
	private static String title = "My Daily Dietary Summary";

	private CardHolder cardHolder = null;

	public UIDietarySummary() {
		super(new BorderLayout());
		setBorder(BorderFactory.createTitledBorder(""));
		CardHolderDatabase.getInstance().addCardHolderDatabaseObserver(this);
	}

	public void loadDietaryChart(DietaryProfile dietaryProfile) {
		removeAll();
		add(new UIDietaryProfilePieChart(dietaryProfile).getContentPane(),BorderLayout.NORTH);
		add(new UIDeitaryProfileBarChart(dietaryProfile).getContentPane(),BorderLayout.CENTER);
		repaint();
		revalidate();
	}

	@Override
	public void onLogin(CardHolder cardHolder, Integer familyId) {
		removeAll();
		this.cardHolder = cardHolder;
		cardHolder.getDietary().addDietaryProfileObserver(this);
		loadDietaryChart(cardHolder.getDietary());
		setBorder(BorderFactory.createTitledBorder("My Dietary Summary"));
		
	}

	@Override
	public void onLogout(CardHolder cardHolder, Integer familyId) {
		this.cardHolder = null;
		removeAll();
		setBorder(BorderFactory.createTitledBorder(""));
	}

	@Override
	public void onUpdate(DietaryProfile dietaryProfile) {
		loadDietaryChart(dietaryProfile);

	}
	
	
	private class UIDietaryProfilePieChart extends ApplicationFrame{
		
		
		public UIDietaryProfilePieChart(DietaryProfile dietaryProfile) {
                super(title);
                final DefaultPieDataset dataSet = createDataset(dietaryProfile);
                final JFreeChart chart = createChart(dataSet);
                final ChartPanel chartPanel = new ChartPanel(chart);
                chartPanel.setPreferredSize(new java.awt.Dimension(500, 200));
                setContentPane(chartPanel);
        }

        private DefaultPieDataset createDataset(DietaryProfile dietaryProfile) {
        		DefaultPieDataset result = new DefaultPieDataset();
        		
        		DietaryEntry dietaryEntry = dietaryProfile.getDietEntries().getLast();
        		if(dietaryEntry != null) {
        			Calendar dateDate = dietaryEntry.getDate();
    				Calendar today = Calendar.getInstance();
    				if ((today.get(Calendar.DAY_OF_MONTH) == dateDate
    						.get(Calendar.DAY_OF_MONTH))
    						&& (today.get(Calendar.MONTH) == dateDate
    								.get(Calendar.MONTH))
    						&& (today.get(Calendar.YEAR) == dateDate
    								.get(Calendar.YEAR))) {
    					int con = dietaryEntry.getConsumed();
    					 result.setValue("Used", con);
     					
    					 result.setValue("Available", dietaryProfile.getCalories());
                	    
    				} else {
    					  result.setValue("Used", 0);
                          
    					 result.setValue("Available", dietaryProfile.getCalories());
                	   
    				}
        		} else {
        			 result.setValue("Used", 0);
                     
        			 result.setValue("Available", dietaryProfile.getCalories());
            	    
        		}
        		 
                
               
                return result;
             
        }

        private JFreeChart createChart(final  PieDataset dataset) { 
        	      
        	JFreeChart chart = ChartFactory.createPieChart(
        	            "My Dietary Summary",  // chart title
        	            dataset,                // data
        	            true,                   // include legend
        	            true,
        	            false
        	        );
        	    PiePlot plot = (PiePlot)chart.getPlot();
              plot.setSectionPaint(0, Color.RED);
              plot.setSectionPaint(1, Color.GREEN);
              return chart;
        }

	}

	private class UIDeitaryProfileBarChart extends ApplicationFrame {

		public UIDeitaryProfileBarChart(DietaryProfile diet) {
			super(title);
			final CategoryDataset dataset = createDataset(diet);
			final JFreeChart chart = createChart(dataset);
			final ChartPanel chartPanel = new ChartPanel(chart);
			chartPanel.setPreferredSize(new java.awt.Dimension(500, 400));
			setContentPane(chartPanel);
		}

		private CategoryDataset createDataset(DietaryProfile diet) {
			DefaultCategoryDataset result = new DefaultCategoryDataset();

			List<DietaryEntry> dietEntries = diet.getDietEntries();
			int index = 0;
			if (dietEntries.size() > UIConstants.CHART_DAYS-1) {
				index = dietEntries.size() - UIConstants.CHART_DAYS-1;
			}
			if(index < 0) {
				index = 0;
			}
			 DietaryEntry todyDietaryEntry = null;
			for (int i = index; i < dietEntries.size(); i++) {
				DietaryEntry dietaryEntry = dietEntries.get(i);
				String date = UIHelper.chartDateFormat.format(dietaryEntry
						.getDate().getTime());
				int con = dietaryEntry.getConsumed();

				Calendar dateDate = dietaryEntry.getDate();
				Calendar today = Calendar.getInstance();
				if ((today.get(Calendar.DAY_OF_MONTH) == dateDate
						.get(Calendar.DAY_OF_MONTH))
						&& (today.get(Calendar.MONTH) == dateDate
								.get(Calendar.MONTH))
						&& (today.get(Calendar.YEAR) == dateDate
								.get(Calendar.YEAR))) {
					
					todyDietaryEntry = dietaryEntry;

				} else {
					int available = dietaryEntry.getAvailable() - con;
					if (available < 0) {
						available = 0;
					}
					result.addValue(con, "Used",date);
					result.addValue(available, "Available", date);
					
				}

			}
			
			if(todyDietaryEntry == null) {
				result.addValue(0, "Used", "Today");
				result.addValue(diet.getCalories(), "Available", "Today");
				
				
			} else {
				int con = todyDietaryEntry.getConsumed();

				int available = diet.getCalories() - con;
				if (available < 0) {
					available = 0;
				}
				
				result.addValue(con, "Used", "Today");
				result.addValue(available, "Available", "Today");
			}
			return result;

		}

		private JFreeChart createChart(final CategoryDataset dataset) {
			final JFreeChart chart = ChartFactory.createStackedBarChart(title,"Calories",
					"Days",  dataset, PlotOrientation.VERTICAL,
					true, true, false);

			GradientPaint gradientpaint0 = new GradientPaint(0.0F, 0.0F,
					Color.RED, 0.0F, 04F, new Color(255, 255, 255));
			GradientPaint gradientpaint1 = new GradientPaint(0.0F, 0.0F,
					Color.GREEN, 0.0F, 0.0F, new Color(255, 255, 255));
			BarRenderer r = (BarRenderer) chart.getCategoryPlot().getRenderer();
			r.setSeriesPaint(0, gradientpaint0);
			r.setSeriesPaint(1, gradientpaint1);

			// r.setDrawBarOutline(false);
			// r.setBaseItemLabelGenerator(
			// new StandardCategoryItemLabelGenerator());
			// r.setBaseItemLabelsVisible(true);
			// r.setBasePositiveItemLabelPosition(new ItemLabelPosition(
			// ItemLabelAnchor.CENTER, TextAnchor.CENTER));
			// r.setBaseNegativeItemLabelPosition(new ItemLabelPosition(
			// ItemLabelAnchor.CENTER, TextAnchor.CENTER));
			// r.setPositiveItemLabelPositionFallback((new ItemLabelPosition(
			// ItemLabelAnchor.CENTER, TextAnchor.CENTER)));
			// r.setNegativeItemLabelPositionFallback((new ItemLabelPosition(
			// ItemLabelAnchor.CENTER, TextAnchor.CENTER)));
			return chart;
		}

	}

}